<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="90px">
          <el-form-item label="订单编号" prop="goodsOrderId">
            <el-input v-model="queryParams.goodsOrderId" placeholder="请输入订单编号" clearable style="width: 240px"
                      @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item label="商品id" prop="goodsId">
            <el-input v-model="queryParams.goodsId" placeholder="请输入商品id" clearable style="width: 240px"
                      @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入商品名称" clearable style="width: 240px"
                      @keyup.enter="handleQuery"/>
          </el-form-item>
          <!--          <el-form-item label="商品价格" prop="price">-->
          <!--            <el-input v-model="queryParams.price" placeholder="请输入商品价格" clearable style="width: 240px" @keyup.enter="handleQuery" />-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="商品介绍" prop="info">-->
          <!--            <el-input v-model="queryParams.info" placeholder="请输入商品介绍" clearable style="width: 240px" @keyup.enter="handleQuery" />-->
          <!--          </el-form-item>-->
          <el-form-item label="订单状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
              <el-option
                v-for="dict in order_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="联系手机号" prop="phone">
            <el-input v-model="queryParams.phone" placeholder="请输入联系手机号" clearable style="width: 240px"
                      @keyup.enter="handleQuery"/>
          </el-form-item>
          <!--          <el-form-item label="游戏ID" prop="gameIdNo">-->
          <!--            <el-input v-model="queryParams.gameIdNo" placeholder="请输入游戏ID" clearable style="width: 240px" @keyup.enter="handleQuery" />-->
          <!--          </el-form-item>-->
          <el-form-item label="打手id" prop="waiterId">
            <el-input v-model="queryParams.waiterId" placeholder="请输入打手id" clearable style="width: 240px"
                      @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['business:order:add']">新增</el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['business:order:edit']">修改</el-button>-->
          <!--          </el-col>-->
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
                       v-hasPermi="['business:order:remove']">删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
                       v-hasPermi="['business:order:export']">导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="订单编号" align="center" prop="goodsOrderId" v-if="true"/>
        <!--        <el-table-column label="商品id" align="center" prop="goodsId" />-->
        <el-table-column label="商品名称" align="center" prop="name"/>
        <el-table-column label="商品图片" align="center" prop="urlLink" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.urlLink" :width="80" :height="80"/>
          </template>
        </el-table-column>
        <el-table-column label="商品价格" align="center" prop="price"/>
        <!--        <el-table-column label="商品介绍" align="center" prop="info" />-->
        <el-table-column label="一级分类" align="center" prop="oneType"/>
        <el-table-column label="二级分类" align="center" prop="type"/>
        <el-table-column label="订单状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="order_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="下单人" align="center" prop="userName"/>
        <el-table-column label="下单时间" align="center" prop="createTime"/>
        <el-table-column label="联系手机号" align="center" prop="phone"/>
        <el-table-column label="游戏ID" align="center" prop="gameIdNo"/>
        <el-table-column label="游戏区服" align="center" prop="gameAreaType"/>
        <el-table-column label="下单备注" align="center" prop="remark"/>
        <!--        <el-table-column label="打手id" align="center" prop="waiterId" />-->
        <el-table-column label="打手" align="center" prop="waiterName"/>
        <el-table-column label="打手队友" align="center" prop="memberIdsName"/>
        <el-table-column label="服务截图" align="center" prop="serverImgUrl" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.serverImgUrl" :width="80" :height="80"/>
          </template>
        </el-table-column>
        <el-table-column label="服务备注" align="center" prop="serverRemark"/>
        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template #default="scope">
            <el-button link type="warning" @click="handleDispatch(scope.row)"
                       v-if="scope.row.status == 2 || scope.row.status == 3">派单
            </el-button>
            <el-button link type="primary" @click="handleEnd(scope.row)"
                       v-if="scope.row.status == 4">结单
            </el-button>
            <el-button link type="danger" @click="handleRefund(scope.row.goodsOrderId)"
                       v-if="scope.row.status > 1 && scope.row.status !=6 ">退款
            </el-button>
            <el-button link type="success" @click="handleReturn(scope.row.goodsOrderId)"
                       v-if="scope.row.status ==3 || scope.row.status == 4 ">回单
            </el-button>
            <el-tooltip content="评论" placement="top">
              <el-button link type="primary" icon="ChatLineRound" @click="goInfo(scope.row.goodsOrderId)"
                         v-hasPermi="['business:watch:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                         v-hasPermi="['business:order:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                         v-hasPermi="['business:order:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改订单对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="50%" append-to-body>
      <el-form ref="orderFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="商品id" prop="goodsId">
          <el-input v-model="form.goodsId" placeholder="请输入商品id"/>
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称"/>
        </el-form-item>
        <el-form-item label="商品图片" prop="url">
          <image-upload v-model="form.url"/>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入商品价格"/>
        </el-form-item>
        <el-form-item label="商品介绍" prop="info">
          <el-input v-model="form.info" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in order_status"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="联系手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系手机号"/>
        </el-form-item>
        <el-form-item label="游戏ID" prop="gameIdNo">
          <el-input v-model="form.gameIdNo" placeholder="请输入游戏ID"/>
        </el-form-item>
        <el-form-item label="下单备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="打手id" prop="waiterId">
          <el-input v-model="form.waiterId" placeholder="请输入打手id"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--    派单-->
    <el-dialog :title="dispatchDialog.title" v-model="dispatchDialog.visible" width="500px" append-to-body>
      <el-form ref="dispatchFormRef" :model="dispatchForm" :rules="rules" label-width="80px">
        <el-form-item label="打手" prop="paymentTime">
          <el-select v-model="dispatchForm.userId" placeholder="请选择打手" clearable filterable>
            <el-option
              v-for="user in examinersList"
              :key="user.userId"
              :label="user.nickName"
              :value="user.userId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitDispatch">确 定</el-button>
          <el-button @click="dispatchDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order" lang="ts">
import {
  listOrder,
  getOrder,
  delOrder,
  addOrder,
  updateOrder,
  dispatchApi,
  getExaminersApi,
  refundApi,
  endOrder, againOrder
} from "@/api/business/order";
import {OrderVO, OrderQuery, OrderForm} from '@/api/business/order/types';

const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const {order_status} = toRefs<any>(proxy?.useDict('order_status'));

const orderList = ref<OrderVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const orderFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: OrderForm = {
  goodsOrderId: undefined,
  goodsId: undefined,
  name: undefined,
  url: undefined,
  price: undefined,
  info: undefined,
  oneType: undefined,
  type: undefined,
  status: undefined,
  phone: undefined,
  gameIdNo: undefined,
  gameAreaType: undefined,
  remark: undefined,
  waiterId: undefined,
}
const data = reactive<PageData<OrderForm, OrderQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    goodsId: undefined,
    name: undefined,
    url: undefined,
    price: undefined,
    info: undefined,
    oneType: undefined,
    type: undefined,
    status: undefined,
    phone: undefined,
    gameIdNo: undefined,
    gameAreaType: undefined,
    waiterId: undefined,
    params: {}
  },
  rules: {
    goodsOrderId: [
      {required: true, message: "订单编号不能为空", trigger: "blur"}
    ],
    goodsId: [
      {required: true, message: "商品id不能为空", trigger: "blur"}
    ],
    name: [
      {required: true, message: "商品名称不能为空", trigger: "blur"}
    ],
    url: [
      {required: true, message: "商品图片不能为空", trigger: "blur"}
    ],
    price: [
      {required: true, message: "商品价格不能为空", trigger: "blur"}
    ],
    info: [
      {required: true, message: "商品介绍不能为空", trigger: "blur"}
    ],
    oneType: [
      {required: true, message: "一级分类不能为空", trigger: "change"}
    ],
    type: [
      {required: true, message: "二级分类不能为空", trigger: "change"}
    ],
    status: [
      {required: true, message: "订单状态不能为空", trigger: "change"}
    ],
    phone: [
      {required: true, message: "联系手机号不能为空", trigger: "blur"}
    ],
    gameIdNo: [
      {required: true, message: "游戏ID不能为空", trigger: "blur"}
    ],
    gameAreaType: [
      {required: true, message: "游戏区服不能为空", trigger: "change"}
    ],
    remark: [
      {required: true, message: "下单备注不能为空", trigger: "blur"}
    ],
    waiterId: [
      {required: true, message: "打手id不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询订单列表 */
const getList = async () => {
  loading.value = true;
  const res = await listOrder(queryParams.value);
  orderList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  orderFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: OrderVO[]) => {
  ids.value = selection.map(item => item.goodsOrderId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加订单";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: OrderVO) => {
  reset();
  const _goodsOrderId = row?.goodsOrderId || ids.value[0]
  const res = await getOrder(_goodsOrderId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改订单";
}

/** 提交按钮 */
const submitForm = () => {
  orderFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.goodsOrderId) {
        await updateOrder(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addOrder(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: OrderVO) => {
  const _goodsOrderIds = row?.goodsOrderId || ids.value;
  await proxy?.$modal.confirm('是否确认删除订单编号为"' + _goodsOrderIds + '"的数据项？').finally(() => loading.value = false);
  await delOrder(_goodsOrderIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

const handleRefund = async (orderId?: any) => {
  await proxy?.$modal.confirm('是否确认退款编号为"' + orderId + '"的订单？').finally(() => loading.value = false);
  await refundApi(orderId);
  proxy?.$modal.msgSuccess("退款成功");
  await getList();
}
const handleReturn = async (orderId?: any) => {
  await proxy?.$modal.confirm('是否确认回单编号为"' + orderId + '"的订单？').finally(() => loading.value = false);
  await againOrder(orderId);
  proxy?.$modal.msgSuccess("回单成功");
  await getList();
}
/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('business/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

//派单
const dispatchForm = ref({
  orderId: undefined,
  userId: undefined,
});
const dispatchDialog = reactive<DialogOption>({
  visible: false,
  title: '派单'
});
const handleDispatch = (row) => {
  dispatchDialog.visible = true;
  dispatchForm.value.orderId = row.goodsOrderId;
  getExaminersList(row.oneTypeId);
}
const submitDispatch = () => {
  dispatchApi(dispatchForm.value).then((res) => {
    if (res.code === 200) {
      dispatchDialog.visible = false;
      proxy?.$modal.msgSuccess("派单成功");
      getList();
    }
  })
}
//结单
const handleEnd = async (row?: OrderVO) => {
  await proxy?.$modal.confirm('是否确认结单').finally(() => loading.value = false);
  await endOrder(row.goodsOrderId);
  proxy?.$modal.msgSuccess("结单成功");
  await getList();
}

const examinersList = ref([]);
const getExaminersList = (typeIds) => {
  const params = {
    isWaiter: "1",
    status: "0",
    typeIds: typeIds
  }
  getExaminersApi(params).then((res) => {
    examinersList.value = res.rows;
  })
}
const router = useRouter();
const goInfo = async (orderId: string) => {
  router.push({path: 'post', query: {orderId}})
}
onMounted(() => {
  getList();
});
</script>
